﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    [DynamicApiController]
    public class UserController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public UserController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }
        public async Task<IActionResult> PostList()
        {
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端用户登录
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAlogin([FromForm] string mobile, [FromForm] string password)
        {
            password = MD5Encryption.Encrypt(password);
            Employee employee = await db.Queryable<Employee>().Mapper(ep => ep.Department, ep => ep.Dpid, ep => ep.Department.Id).Where(ep => ep.Mobile == mobile && ep.Password == password && ep.Status == "ok").FirstAsync();

            if (employee == null) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            UnifyContext.Fill(new { Token = MD5Encryption.Encrypt("123456") });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = employee,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-用户退出
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAlogout([FromForm] long eid, [FromForm] long epid)
        {
            await db.Updateable<Employee>().SetColumns(ep => ep.DefaultEid == eid).Where(ep => ep.Id == epid).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 企业端登录
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostElogin([FromForm] string mobile, [FromForm] string password)
        {
            password = MD5Encryption.Encrypt(password);
            Enterprise enterprise = await db.Queryable<Enterprise>().Where(e => e.Mobile == mobile && e.Password == password).SingleAsync();

            if (enterprise == null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            UnifyContext.Fill(new { Token = MD5Encryption.Encrypt("123456") });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = enterprise,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 企业注册
        /// </summary>
        /// <param name="enterprise"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostEregister([FromForm] Enterprise enterprise)
        {
            enterprise.Password = MD5Encryption.Encrypt(enterprise.Password);
            // 如果该手机号已注册提示失败
            Enterprise existsEnterprise = await db.Queryable<Enterprise>().Where(e => e.Mobile == enterprise.Mobile).SingleAsync();
            if (existsEnterprise != null) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该手机号已注册",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            long eid = await db.Insertable<Enterprise>(enterprise).ExecuteReturnIdentityAsync();
            // 给该企业添加权限
            List<BasePermission> basepermissions = await db.Queryable<BasePermission>().Where(bp => bp.IndustryType == enterprise.IndustryType).ToListAsync();
            List<EnterprisePermission> enterprisePermissions = new();
            foreach (var basepermission in basepermissions)
            {
                enterprisePermissions.Add(new EnterprisePermission { Eid = eid, Bspmid = basepermission.Id, ActionKey = basepermission.ActionKey, Node = basepermission.Node, Type = basepermission.Type, Path = basepermission.Path, Name = basepermission.Name, ParentId = basepermission.ParentId, SortId = basepermission.SortId, Status = 1 });
            }
            await db.Insertable<EnterprisePermission>(enterprisePermissions).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
